package com.iqiyi.pps.epg.core.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.iqiyi.kiwi.utils.Configuration;
import com.iqiyi.pps.epg.core.model.carousel.ProgramQipuData;
import com.iqiyi.pps.epg.core.model.channel.ChannelBase;
import com.iqiyi.pps.epg.core.model.channel.SearchSettingConfig;
import com.iqiyi.pps.epg.core.model.program.ProgramData;
import com.iqiyi.pps.epg.core.rpc.qipu.impl.QipuManager;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by karkarrotxu on 2015/10/16.
 */
public final class ApiQipuUtil {
   public static final String QIPU_ENTITY_URL = Configuration.getString("qipu.entity.url");
    public static final String ALBUM_SOURCE_TYPE = "album_source_type";
    // public static final String QIPU_ENTITY_URL
    // ="http://qipu-test.qiyi.domain/int/entity/nocache/@.json";
    //   public static final String QIPU_ENTITY_URL = "http://qipu.qiyi.domain/int/entity/nocache/@.json";
    public static final String DISPLAY_NAME = "display_name";
    public static final String AVAILABLE_STATUS = "available_status";
    public static final String AVAILABE_STATUS = "availabe_status";
    public static final String ONLINE = "ONLINE";
    public static final String PLAY_PLATFORM = "play_platform";
    public static final String DEFAULT_CONTROL = "default_control";
    public static final String REGION_CONTROL = "region_control";
    public static final String LOCATION_CONTROL = "location_control";
    public static final String PU_YU = "puyu";
    public static final String COPYRIGHT_OWNER = "copyright_owner";
    public static final String PAIED_AVAILABLE = "PAIED_AVAILABLE";
    public static final String FREE = "FREE";
    public static final String LOCATION = "location";
    public static final String PROVINCE_ID = "province_id";

    public static final String CONTENT_TYPE = "content_type";
    // check pps_platform_region_control ， access_play_control
    public static final String PPS_PLATFORM_REGION_CONTROL = "pps_platform_region_control";
    public static final String ACCESS_PLAY_CONTROL = "access_play_control";
    public static final String PER_PLATFORM_REGION_CONTROL = "per_platform_region_control";
    private static final String EXCLUSIVE_STATUS_IQIYI = "exclusive_status_iqiyi";
    private static final String QITAN = "qitan";
    private static final String IMAGEFORMAT_IQIYI_PC = "imageformat_iqiyi_pc";
    private static final String NAME = "name";
    private static final String VALUE = "value";
    private static final String KEY_VALUE_PAIR = "key_value_pair";
    private static final String BASE = "base";
    private static final String IS_QIYI_PRODUCED = "is_qiyi_produced";
    private static final String SHOULD_DISPLAY = "should_display";
    private static final String ENTITY_ID = "entity_id";
    private static final String TITLE = "title";
    private static final String DESCRIPTION = "description";
    private static final String PROPER_TITLE = "proper_title";
    private static final String METADATA = "metadata";
    private static final String BOSS = "boss";
    private static final String STATUS = "status";
    public static final String LOCAL_BASE = "local_base";
    public static final String LOCAL_TW = "zh_TW";
    private static final String PAGE_PUBLISH_STATUS = "page_publish_status";
    private static final String PAGE_ONLINE = "PAGE_ONLINE";
    private static Logger logger = LoggerFactory.getLogger(ApiQipuUtil.class);

    private static Map<Long, JSONObject> qipuCacheMap = new ConcurrentHashMap<>(512);
    private static long lastUpdateCache = System.currentTimeMillis();
    private static long refreshGap = 120000L;
    private static QipuManager qipuInstance = null;

    private ApiQipuUtil() {
    }

    private static QipuManager getQipuInstance() {
        if (qipuInstance == null) {
            QipuManager qipuManager = (QipuManager) ApplicationContextUtil.getBean(QipuManager.class);
            qipuInstance = qipuManager;
        }
        return qipuInstance;
    }

    public static ProgramQipuData queryByQipuIdAndCheck(long qipuId, SearchSettingConfig searchSettingConfig) {
        if (qipuId < 1) {
            logger.info("illegal: qipuId < 1");
            return createIllegal(qipuId);
        }
        JSONObject dataEntity = getValidCache(qipuId);
        if (dataEntity == null) {
            logger.info("illegal: dataEntity null");
            return createIllegal(qipuId);
        }
        String qipuIdString = dataEntity.getString("id");
        ProgramQipuData element = null;
        try {
            if (qipuIdString.endsWith("09")) {
                element = decodeProgram09(dataEntity);
            } else if (qipuIdString.endsWith("00")) {
                if (checkValidByConfig(dataEntity, searchSettingConfig)) {
                    element = decodeProgram00(dataEntity);
                }
            }
            if (element != null) {
                element.getOriginal().setCarouselEpisode(qipuId);
            }
        } catch (Exception e) {
            if (element != null) {
                logger.info("illegal: element Exception");
                element.setIllegal(true);
                element.getOriginal().setCarouselEpisode(qipuId);
            }
            logger.error("[queryByQipuId][qipuId=" + qipuIdString + "][error={}]", e);
        }
        if (element == null) {
            element = createIllegal(qipuId);
            logger.info("illegal: element empty");
        }
        dataEntity = null;
        return element;
    }

    public static ProgramQipuData queryByQipuIdAndCheck(long qipuId, SearchSettingConfig searchSettingConfig, ChannelBase channelBase) {
        if (qipuId < 1) {
            logger.info("illegal: qipuId < 1");
            return createIllegal(qipuId);
        }
        JSONObject dataEntity = getValidCache(qipuId);
        if (dataEntity == null) {
            logger.info("illegal: dataEntity null");
            return createIllegal(qipuId);
        }
        String qipuIdString = dataEntity.getString("id");
        ProgramQipuData element = null;
        try {
            if (qipuIdString.endsWith("09")) {
                element = decodeProgram09(dataEntity, channelBase);
            } else if (qipuIdString.endsWith("00")) {
                if (checkValidByConfig(dataEntity, searchSettingConfig)) {
                    element = decodeProgram00(dataEntity, channelBase);
                }
            }
            if (element != null) {
                element.getOriginal().setCarouselEpisode(qipuId);
            }
        } catch (Exception e) {
            if (element != null) {
                logger.info("illegal: element Exception");
                element.setIllegal(true);
                element.getOriginal().setCarouselEpisode(qipuId);
            }
            logger.error("[queryByQipuId][qipuId=" + qipuIdString + "][error={}]", e);
        }
        if (element == null) {
            element = createIllegal(qipuId);
            logger.info("illegal: element empty");
        }
        dataEntity = null;
        return element;
    }

    private static ProgramQipuData decodeProgram09(JSONObject dataEntity) {
        ProgramQipuData element = new ProgramQipuData();
        ProgramData original = element.getOriginal();
        // 节目名称
        JSONObject metadata = dataEntity.getJSONObject(METADATA);
        original.setPname(metadata.getJSONObject(TITLE).getString(PROPER_TITLE));

        // 节目名称
        if (metadata.getJSONObject(DESCRIPTION) != null) {
            original.setDescription(metadata.getJSONObject(DESCRIPTION).getString(DESCRIPTION));
        }
        // 弹幕开关
        // 是否奇艺出品
        // 评论关联
        // 屏蔽评论
        // 是否独播

        // 节目时长 （second）
        JSONArray formatArr = dataEntity.getJSONArray("format");
        if (formatArr != null && formatArr.size() > 0) {
            element.setDuration(formatArr.getJSONObject(0).getIntValue("duration"));
        }
        /* ============ */
        JSONArray kvPair = dataEntity.getJSONArray(KEY_VALUE_PAIR);
        if (kvPair != null) {
            Iterator<Object> t = kvPair.iterator();
            JSONObject entity = null;
            while (t.hasNext()) {
                entity = (JSONObject) t.next();
                // 截图编辑
                if (IMAGEFORMAT_IQIYI_PC.equals(entity.getString(NAME))) {
                    original.setDefaultLogoUrl(entity.getString(VALUE));
                }
            }
        }
        return element;
    }

    private static ProgramQipuData decodeProgram09(JSONObject dataEntity, ChannelBase channelBase) {
        ProgramQipuData element = new ProgramQipuData();
        ProgramData original = element.getOriginal();

        String display_name = null;
        String description = null;
        if(channelBase.getType() == 11) {
            JSONArray localbase = dataEntity.getJSONArray(LOCAL_BASE);
            if(null != localbase) {
                Iterator<Object> t = localbase.iterator();
                JSONObject entity = null;
                while (t.hasNext()) {
                    entity = (JSONObject) t.next();
                    if(LOCAL_TW.equals(entity.getString("language"))) {
                        display_name = entity.getString("display_name");

                        if(StringUtils.isBlank(entity.getString("description"))) {
                            description = display_name;
                        }else{
                            description = entity.getString("description");
                        }
                    }
                }
            }
        }

        // 节目名称
        JSONObject metadata = dataEntity.getJSONObject(METADATA);
        if(channelBase.getType() == 11 && null != display_name) {
            original.setPname(display_name);
            original.setDescription(cutString(description, 200));
        }else {
            original.setPname(metadata.getJSONObject(TITLE).getString(PROPER_TITLE));

            // 节目名称
            if (metadata.getJSONObject(DESCRIPTION) != null) {
                original.setDescription(metadata.getJSONObject(DESCRIPTION).getString(DESCRIPTION));
            }
        }
        // 弹幕开关
        // 是否奇艺出品
        // 评论关联
        // 屏蔽评论
        // 是否独播

        // 节目时长 （second）
        JSONArray formatArr = dataEntity.getJSONArray("format");
        if (formatArr != null && formatArr.size() > 0) {
            element.setDuration(formatArr.getJSONObject(0).getIntValue("duration"));
        }
        /* ============ */
        JSONArray kvPair = dataEntity.getJSONArray(KEY_VALUE_PAIR);
        if (kvPair != null) {
            Iterator<Object> t = kvPair.iterator();
            JSONObject entity = null;
            while (t.hasNext()) {
                entity = (JSONObject) t.next();
                // 截图编辑
                if (IMAGEFORMAT_IQIYI_PC.equals(entity.getString(NAME))) {
                    original.setDefaultLogoUrl(entity.getString(VALUE));
                }
            }
        }
        return element;
    }

    private static boolean checkValidByConfig(JSONObject dataEntity, SearchSettingConfig config) {
        if (config == null) {
            config = SettingConfigUtil.getInstance().getDefault();
        } else {
            config.readLimit();
        }
        Long qipuId = dataEntity.getLong("id");
        //过滤未上线节目
        if (!ONLINE.equals(dataEntity.getString(AVAILABLE_STATUS))) {
            logger.info("[checkValid] ONLINE false [qipuId={}]", qipuId);
            return false;
        }
        //匹配过滤 版权
        if (config.getCheckCopyRightType() == 1) {
            if (dataEntity.getJSONObject(PU_YU) == null) {
                logger.info("[checkValid] PU_YU empty [qipuId={}]", qipuId);
                return false;
            }
            JSONArray ownerArr = dataEntity.getJSONObject(PU_YU).getJSONArray(COPYRIGHT_OWNER);
            if (ownerArr == null || ownerArr.size() == 0) {
                logger.info("[checkValid] COPYRIGHT_OWNER empty [qipuId={}]", qipuId);
                return false;
            }
            if (ownerArr.getJSONObject(0).getIntValue("id") < 1) {
                logger.info("[checkValid] COPYRIGHT_OWNER id  error [qipuId={}]", qipuId);
                return false;
            }

        }
        //匹配过滤 付费模式
        if (config.getCheckBossType() == 1) {
            //过滤免费
            if (dataEntity.getJSONObject(BOSS) == null || !PAIED_AVAILABLE.equals(dataEntity.getJSONObject(BOSS).getString(STATUS))) {
                logger.info("[checkValid] PAIED_AVAILABLE false [qipuId={}]", qipuId);
                return false;
            }
        } else if (config.getCheckBossType() == 0) {
            //过滤付费
            if (dataEntity.getJSONObject(BOSS) != null
                    && dataEntity.getJSONObject(BOSS).getString(STATUS) != null
                    && !FREE.equals(dataEntity.getJSONObject(BOSS).getString(STATUS))) {
                logger.info("[checkValid] FREE false [qipuId={}]", qipuId);
                return false;
            }
        }
        //匹配过滤 发布模式
        //过滤掉未发布的节目
        if (config.getCheckPublishType() == 1) {
            if (!PAGE_ONLINE.equals(dataEntity.getString(PAGE_PUBLISH_STATUS))) {
                logger.info("[checkValid] PAGE_ONLINE false [qipuId={}]", qipuId);
                return false;
            }
        }
// 过滤端
        List<String> checkOnlineList = SettingConfigUtil.getInstance().transToClientName(config.getNeedOnlines());
        List<String> checkRegionList = SettingConfigUtil.getInstance().transToClientName(config.getNeedRegions());
        JSONArray accessControlArr = dataEntity.getJSONArray(ACCESS_PLAY_CONTROL);
        if (accessControlArr == null || accessControlArr.isEmpty()) {
            logger.info("[checkValid] ACCESS_PLAY_CONTROL false [qipuId={}]", qipuId);
            return false;
        }
        Iterator<Object> it = accessControlArr.iterator();
        JSONObject nodeElement = null;
        JSONObject controlEntity = null;
        JSONArray region_control = null;
        String playPlatFormName = null;
        while (it.hasNext()) {
            nodeElement = (JSONObject) it.next();
            playPlatFormName = nodeElement.getString(PLAY_PLATFORM);
            if (checkOnlineList.contains(playPlatFormName)) {
                checkOnlineList.remove(playPlatFormName);
                controlEntity = nodeElement.getJSONObject(DEFAULT_CONTROL);
                if (controlEntity == null || !ONLINE.equals(controlEntity.getString(AVAILABE_STATUS))) {
                    logger.info("[checkValid]  DEFAULT_CONTROL false [qipuId={}][play_platform={}]", qipuId, nodeElement.getString("play_platform"));
                    return false;
                }
            }

            if (checkRegionList.contains(playPlatFormName)) {
                region_control = nodeElement.getJSONArray(REGION_CONTROL);
                if (region_control != null) {
                    if (!checkOnlyOverSea(region_control)) {
                        logger.info("[checkValid]  region_control false [qipuId={}][region_control={}]", qipuId, region_control);
                        return false;
                    }
                }
            }
        }
        if (checkOnlineList.size() > 0) {
            logger.info("[checkValid] false [qipuId={}][rest_need_check={}]", qipuId, checkOnlineList.toString());
            return false;
        }
        return true;
    }

    //香港:95;澳门:148;台湾:228
    private static boolean checkOnlyOverSea(JSONArray region_control) {
        JSONObject locationNode = null;
        JSONObject lControl = null;
        JSONArray localtionArr = null;
        Iterator<Object> lIt = null;
        Iterator<Object> rControlIt = region_control.iterator();
        JSONObject element = null;
        Integer provinceId = null;
        while (rControlIt.hasNext()) {
            locationNode = (JSONObject) rControlIt.next();
            localtionArr = locationNode.getJSONArray(LOCATION);
            if (localtionArr == null) {
                continue;
            }
            lIt = localtionArr.iterator();
            while (lIt.hasNext()) {
                element = (JSONObject) lIt.next();
                provinceId = element.getInteger(PROVINCE_ID);
                if (provinceId != null) {
                    if (provinceId != 95 && provinceId != 148 && provinceId != 228) {
                        lControl = locationNode.getJSONObject(LOCATION_CONTROL);
                        if (lControl != null && !ONLINE.equals(lControl.getString(AVAILABE_STATUS))) {
                            return false;
                        }
                    }
                }
            }
        }
        return true;
    }

    public static Integer getAlbumSourceTypeQipuData(long qipuId) {
        if (!(qipuId + "").endsWith("01")) {
            return null;
        }
        JSONObject dataEntity = rpcReadQipuEntity(qipuId) ;
        JSONArray kvPair = dataEntity.getJSONArray(KEY_VALUE_PAIR);
        if (kvPair != null) {
            Iterator<Object> t = kvPair.iterator();
            JSONObject entity = null;
            while (t.hasNext()) {
                entity = (JSONObject) t.next();
                // 专辑 类型

                if (ALBUM_SOURCE_TYPE.equals(entity.getString(NAME))) {
                    return entity.getInteger(VALUE);
                }
            }
        }
        return null;
    }

    private static ProgramQipuData decodeProgram00(JSONObject dataEntity) {
        ProgramQipuData element = new ProgramQipuData();
        ProgramData original = element.getOriginal();
        JSONObject base = dataEntity.getJSONObject(BASE);
        if (base == null || base.isEmpty()) {
            return null;
        }

        original.setPname(base.getString(DISPLAY_NAME));
        JSONObject metadata = dataEntity.getJSONObject(METADATA);

        if (metadata.getJSONObject(DESCRIPTION) != null) {
            String description = metadata.getJSONObject(DESCRIPTION).getString(DESCRIPTION);
            if (description != null) {
                if (description.length() > 200) {
                    description = description.substring(0, 200);
                }
                original.setDescription(description);
            } else {
                original.setDescription("");
            }
        }
        // 弹幕开关

        // 评论相关
        JSONObject qitan = dataEntity.getJSONObject(QITAN);
        if (qitan != null) {
            // 评论关联
            if (qitan.containsKey(ENTITY_ID)) {
                original.setQitanId(qitan.getLongValue(ENTITY_ID));
            }
            // 屏蔽评论
            if (qitan.containsKey(SHOULD_DISPLAY)) {
                original.setAllowComment(qitan.getBooleanValue(SHOULD_DISPLAY) ? 1 : 0);
            }
        }
        // 是否奇艺出品

        if (base.containsKey(IS_QIYI_PRODUCED)) {
            original.setQiyiProduct(base.getBooleanValue(IS_QIYI_PRODUCED) ? 1 : 0);
        }

        // 记录节目的内容类型
        //content_type
        if (base.containsKey(CONTENT_TYPE)) {
            element.setReferContentType(base.getString(CONTENT_TYPE));
        }
        // 节目时长 （s）
        JSONArray formatArr = dataEntity.getJSONArray("format");
        if (formatArr != null && formatArr.size() > 0) {
            element.setDuration(formatArr.getJSONObject(0).getIntValue("duration"));
        }
        /* ============ */
        JSONArray kvPair = dataEntity.getJSONArray(KEY_VALUE_PAIR);
        if (kvPair != null) {
            Iterator<Object> t = kvPair.iterator();
            JSONObject entity = null;
            while (t.hasNext()) {
                entity = (JSONObject) t.next();
                // 截图编辑
                if (IMAGEFORMAT_IQIYI_PC.equals(entity.getString(NAME))) {
                    original.setDefaultLogoUrl(entity.getString(VALUE));
                }
                // 是否独播
                if (EXCLUSIVE_STATUS_IQIYI.equals(entity.getString(NAME))) {
                    original.setQiyiExclusive(entity.getIntValue(VALUE));
                }
            }
        }

        //
        return element;
    }

    private static ProgramQipuData decodeProgram00(JSONObject dataEntity, ChannelBase channelBase) {
        ProgramQipuData element = new ProgramQipuData();
        ProgramData original = element.getOriginal();
        JSONObject base = dataEntity.getJSONObject(BASE);
        if (base == null || base.isEmpty()) {
            return null;
        }

        String twDisplay_name = null;
        String twDescription = null;
        if(channelBase.getType() == 11) {
            JSONArray localbase = dataEntity.getJSONArray(LOCAL_BASE);
            if(null != localbase) {
                Iterator<Object> t = localbase.iterator();
                JSONObject entity = null;
                while (t.hasNext()) {
                    entity = (JSONObject) t.next();
                    if(LOCAL_TW.equals(entity.getString("language"))) {
                        twDisplay_name = entity.getString("display_name");

                        if(StringUtils.isBlank(entity.getString("description"))) {
                            twDescription = twDisplay_name;
                        }else{
                            twDescription = entity.getString("description");
                        }
                    }
                }
            }
        }

        if(channelBase.getType() == 11 && null != twDisplay_name) {
            original.setPname(twDisplay_name);
            original.setDescription(cutString(twDescription, 200));
        }else {
            original.setPname(base.getString(DISPLAY_NAME));
            JSONObject metadata = dataEntity.getJSONObject(METADATA);

            if (metadata.getJSONObject(DESCRIPTION) != null) {
                String description = metadata.getJSONObject(DESCRIPTION).getString(DESCRIPTION);
                if (description != null) {
                    if (description.length() > 200) {
                        description = description.substring(0, 200);
                    }
                    original.setDescription(description);
                } else {
                    original.setDescription("");
                }
            }
        }
        // 弹幕开关

        // 评论相关
        JSONObject qitan = dataEntity.getJSONObject(QITAN);
        if (qitan != null) {
            // 评论关联
            if (qitan.containsKey(ENTITY_ID)) {
                original.setQitanId(qitan.getLongValue(ENTITY_ID));
            }
            // 屏蔽评论
            if (qitan.containsKey(SHOULD_DISPLAY)) {
                original.setAllowComment(qitan.getBooleanValue(SHOULD_DISPLAY) ? 1 : 0);
            }
        }
        // 是否奇艺出品

        if (base.containsKey(IS_QIYI_PRODUCED)) {
            original.setQiyiProduct(base.getBooleanValue(IS_QIYI_PRODUCED) ? 1 : 0);
        }

        // 记录节目的内容类型
        //content_type
        if (base.containsKey(CONTENT_TYPE)) {
            element.setReferContentType(base.getString(CONTENT_TYPE));
        }
        // 节目时长 （s）
        JSONArray formatArr = dataEntity.getJSONArray("format");
        if (formatArr != null && formatArr.size() > 0) {
            element.setDuration(formatArr.getJSONObject(0).getIntValue("duration"));
        }
        /* ============ */
        JSONArray kvPair = dataEntity.getJSONArray(KEY_VALUE_PAIR);
        if (kvPair != null) {
            Iterator<Object> t = kvPair.iterator();
            JSONObject entity = null;
            while (t.hasNext()) {
                entity = (JSONObject) t.next();
                // 截图编辑
                if (IMAGEFORMAT_IQIYI_PC.equals(entity.getString(NAME))) {
                    original.setDefaultLogoUrl(entity.getString(VALUE));
                }
                // 是否独播
                if (EXCLUSIVE_STATUS_IQIYI.equals(entity.getString(NAME))) {
                    original.setQiyiExclusive(entity.getIntValue(VALUE));
                }
            }
        }

        //
        return element;
    }

    public static List<Long> filterChildren(JSONObject dataEntity, int startIndex, int limit) {
        JSONArray dataArr = dataEntity.getJSONArray("episode_summary");
        List<Long> children = new ArrayList<Long>();
        Iterator<Object> it = dataArr.iterator();
        JSONObject nodeElement = null;
        int currentIndex = -1;
        while (it.hasNext()) {
            nodeElement = (JSONObject) it.next();
            currentIndex++;
            if (currentIndex < startIndex) {
                continue;
            }
            children.add(nodeElement.getLong(ENTITY_ID));
            if (children.size() == limit) {
                break;
            }
        }
        return children;
    }

    public static List<Long> filterChildren(JSONObject dataEntity) {
        JSONArray dataArr = dataEntity.getJSONArray("episode_summary");
        List<Long> children = new ArrayList<Long>();
        Iterator<Object> it = dataArr.iterator();
        JSONObject nodeElement = null;
        while (it.hasNext()) {
            nodeElement = (JSONObject) it.next();
            children.add(nodeElement.getLong(ENTITY_ID));
        }
        return children;
    }

    private static ProgramQipuData createIllegal(long qipuId) {
        ProgramQipuData element = new ProgramQipuData();
        ProgramData original = element.getOriginal();
        original.setCarouselEpisode(qipuId);
        original.setPname("delete" + qipuId);
        element.setIllegal(true);
        return element;
    }

    public static List<Long> getEpisodeChildren(Long qipuId) {
        List<Long> children = new ArrayList<Long>();
        JSONObject dataEntity = rpcReadQipuEntity(qipuId);
        if (dataEntity == null) {
            logger.info("[ApiQipuUtil][getEpisodeChildren] 未取到奇谱数据,qipuId:{}", qipuId);
            return children;
        }
        int rest = (int) (qipuId - qipuId / 100 * 100);
        switch (rest) {
            case 1:
            case 2:
                children = filterChildren(dataEntity);
                break;
        }
        if (children == null) {
            children = new ArrayList<Long>();
        }

        return children;
    }

    public static boolean checkHasPPSControlAndAccessControl(JSONObject jsonObject) {
        boolean flag = false;
        if (jsonObject == null) {
            logger.info("[checkHasPPSControlAndAccessControl] [jsonObject is empty]");
            return flag;
        }
        Long qipuId = jsonObject.getLong("id");
        try {
//            不判断 pps 端 播控设定
//            JSONObject ppsObject = jsonObject.getJSONObject(PPS_PLATFORM_REGION_CONTROL);
//            if (null == ppsObject) {
//                logger.info("[checkHasPPSControlAndAccessControl] check fail [qipuId={}][pps empty={}][all empty={}]", qipuId, null == ppsObject);
//                return false;
//
//            }
//            JSONArray perArr = ppsObject.getJSONArray(PER_PLATFORM_REGION_CONTROL);
//            if (null == perArr || 0 == perArr.size()) {
//                logger.info("[checkHasPPSControlAndAccessControl] pps control check fail [qipuId={}]", qipuId);
//                return false;
//            }
            JSONArray allControlObject = jsonObject.getJSONArray(ACCESS_PLAY_CONTROL);
            if (null == allControlObject || 0 == allControlObject.size()) {
                logger.info("[checkHasPPSControlAndAccessControl] check allControlObject [qipuId={}][all empty={}]", qipuId, null == allControlObject);
                return false;
            }
            flag = true;
        } catch (Exception e) {
            logger.error("[checkHasPPSControlAndAccessControl] [qipuId==" + qipuId + "]Exception={}", e);
        }
        return flag;
    }

    public static JSONObject getValidCache(long key) {
        long current = System.currentTimeMillis();
        JSONObject cache = null;
        synchronized (qipuCacheMap) {
            if (current - lastUpdateCache > refreshGap) {
                lastUpdateCache = current;
                qipuCacheMap.clear();
            }
            cache = qipuCacheMap.get(key);
            if (cache == null) {
//                cache =  ApiHttpRequestUtil.getMethod(QIPU_ENTITY_URL.replace("@", key + ""), new HashMap<String, Object>());
                cache = JSONObject.parseObject(getQipuInstance().getQipuEntityData(key));
                if (cache == null) {
                    logger.warn("qipuId={}, decode error", key);
                } else {
                    qipuCacheMap.put(key, cache);
                }
            }
        }
        return cache;
    }

    public static String rpcReadQipuEntityStr(long qipuId) {
        QipuManager qipuManager = getQipuInstance();
        if (qipuManager != null) {
            try {
                return qipuManager.getQipuEntityData(qipuId);
            } catch (Exception e) {
                logger.error(" rpcReadQipuEntityStr:" + qipuId, e);
            }
        }
        return null;
    }

    public static JSONObject rpcReadQipuEntity(long qipuId) {
        String jsonString = rpcReadQipuEntityStr(qipuId);
        if (jsonString != null) {
            return JSONObject.parseObject(jsonString);
        }
        return null;
    }

    public static String getQipuEntityUrl(long qipuId) {
        return QIPU_ENTITY_URL.replace("@", "" + qipuId);
    }

    public static String cutString(String str, int length) {
        if(null == str) {
            return str;
        }

        if (str.length() > length) {
            return str.substring(0, length);
        }
        return str;
    }
}
